using System;
using System.Collections;
using UnityEngine;

namespace ClassicBehaviorTree
{
    public class TimerNode : Node
    {
        private int _duration;
        private int _remainFrame;
        private IEnumerator _timer;
        private TimerPattern _pattern;

        public int Duration { get => _duration; set => _duration = Mathf.Max(0, value); }
        public int RemainFrame { get => _remainFrame; set => _remainFrame = Mathf.Max(0, value); }
        public TimerNode() { }
        public TimerNode(TimerPattern pattern, int duration)
        {
            Duration = duration;
            _pattern = pattern;
        }
        public TimerNode(string pattern, int duration)
        {
            Duration = duration;
            _pattern = (TimerPattern)Enum.Parse(typeof(TimerPattern), pattern);
        }
        public TimerNode(string pattern, string duration)
        {
            Duration = int.Parse(duration);
            _pattern = (TimerPattern)Enum.Parse(typeof(TimerPattern), pattern);
        }
        private IEnumerator Timer()
        {
            while (RemainFrame > 0)
            {
                RemainFrame--;
                yield return null;
            }
            switch (_pattern)//will run after yield return
            {
                case TimerPattern.While:
                    _state = NodeState.Failure;
                    break;
                case TimerPattern.Until:
                    _state = NodeState.Success;
                    break;
                default:
                    break;
            }
        }
        public override void Initialize(MonoBehaviour behaviorTree)
        {
            base.Initialize(behaviorTree);
            _timer = null;
        }
        public override NodeState Update()
        {
            if (_timer == null)
            {
                switch (_pattern)
                {
                    case TimerPattern.While:
                        _state = NodeState.Success;
                        break;
                    case TimerPattern.Until:
                        _state = NodeState.Ready;
                        break;
                    default:
                        break;
                }
                RemainFrame = Duration;
                _timer = Timer();
                _behaviorTree.StartCoroutine(_timer);
            }
            return _state;
        }
        public override void Reset()
        {
            base.Reset();
            _timer = null;
        }
    }
}
